<template>
  <div class="home">
    <input type="text" v-model="title" />
    <button @click="add">添加</button>

    <van-tabs v-model="active">
      <van-tab
        v-for="(item, index) in navs"
        :key="index"
        :title="item.title"
      ></van-tab>
    </van-tabs>

    <ul class="con">
      <button @click="sorttime">时间排序</button>
      <li v-for="(item, index) in cons[this.active].list" :key="index">
        <input
          v-if="index == editIndex"
          type="text"
          v-model="item.name"
          @blur="editIndex = -1"
        />
        <span v-else style="margin-right:50px" @dblclick="edit(index)"
          >{{ item.name }}
        </span>
        <span style="margin-right:50px">{{ item.time | filtime }}</span>
        <a href="#" @click="remove(index)">x</a>
      </li>
    </ul>
  </div>
</template>

<script>
// @ is an alias to /src

export default {
  data() {
    return {
      active: 0,
      title: "",
      navs: [
        { title: "电影" },
        { title: "书籍" },
        { title: "综艺" },
        { title: "体育节目" },
        { title: "游戏" },
      ],
      cons: [
        { list: [{ name: "肖申克的救赎", time: new Date() }] },
        { list: [{ name: "围墙", time: new Date() }] },
        { list: [{ name: "王牌对王牌", time: new Date() }] },
        { list: [{ name: "nba", time: new Date() }] },
        { list: [{ name: "王者荣耀", time: new Date() }] },
      ],
      editIndex: -1,
    };
  },
  methods: {
    add() {
      if (this.title == "") {
        alert("不能为空");
        return false;
      }
      //判空
      let flag = false;
      //判断要添加的内容是否存在
      this.cons[this.active].list.forEach((item) => {
        if (item.name == this.title) {
          flag = true;
          alert("不能重复添加");
        }
        //一旦相等了证明要添加的内容存在了，flag就变成true
      });

      if (flag == false) {
        this.cons[this.active].list.push({
          name: this.title,
          time: new Date(),
        });
        this.title = "";
      }
      //循环结束之后才能知道这个数据存不存在，如果还是false证明不存在，就往里添加
    },
    remove(xcm) {
      this.cons[this.active].list.splice(xcm, 1);
    },
    sorttime() {
      this.cons[this.active].list.sort((a, b) => {
        console.log(b.time);
        return b.time - a.time;
      });
    },
    edit(i) {
      console.log(i);
      this.editIndex = i;
    },
  },
  filters: {
    filtime(val) {
      return new Date(val).toLocaleString();
    },
  },
};
</script>
<style lang="scss">
.home {
  width: 500px;
  margin: 0 auto;
}
.con {
  li {
    display: flex;
    // justify-content: space-between;
  }
  a {
    display: none;
  }
}
.con li:hover {
  background: chocolate;
  a {
    display: inline-block;
  }
}
</style>
